<script setup lang="ts">
import { ref,toRaw } from 'vue'
import { articleListService, addArticleService, 
        updateArticleService, deleteArticleService,
        deleteBatchArticleService,selectArticleCategory } from "@/api/article"
import { ElMessage, ElMessageBox } from 'element-plus'
import TextEditor from '@/component/TextEditor.vue'
import {
    Edit,
    Delete,
} from '@element-plus/icons-vue'

const article = ref([
    {
        "id": 1,
        "title": "测试",
        "content": "测试",
        "description": "测试",
        "author": "zhangSan",
        "createTime":"",
        "category":"测试"
    }
])
//条件搜索模型
const title = ref('');
const category = ref('');
//分页条数据模型
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数
//文章分类列表集合
const categories = ref([]);
const articleCategoryList = async () =>{
    let result = await selectArticleCategory();
    categories.value = result.data;
}
const articleList = async () => {
    let params = {
        page: page.value,
        pageSize: pageSize.value,
        title: title.value ? title.value : null,
        category: category.value ? category.value : null,
    }
    let result = await articleListService(params)

    //渲染视图
    total.value = result.data.total;
    article.value = result.data.records;
}
//调用函数查询
articleList();
//当每页条数发生了变化，调用此函数
const handleSizeChange = (size: number) => {
    pageSize.value = size
    articleList();
}
//当前页码发生变化，调用此函数
const handleCurrentChange = (num: number) => {
    page.value = num
    articleList();
}
//通过按钮点击展示内容（因为富文本大多时候内容很长）
const content1 = ref("")
const visibleDialog1 = ref(false)
const showContent = (content: string) =>{
    visibleDialog1.value = true
    content1.value = content
}
//添加、修改会员表单模型
const articleForm = ref({
    id: 1 ,
    title: "",
    content: "",
    description: "",
    category:""
})
//添加、修改会员的表单校验模型
const Rules = ref({
    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请输入文章分类', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入文章描述', trigger: 'blur' }
    ]
})

//默认不显示抽屉
const visibleDrawer = ref(false)
//为抽屉添加响应数据
const addArticleRef = ref()
//后台调用添加用户接口
const onAdd = async () => {
    //点击添加按钮后再进行二次校验
    await addArticleRef.value?.validate().catch((err: any) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await addArticleService(articleForm.value) as any;
    ElMessage.success(result.msg ? result.msg : '添加成功')
    //让抽屉消失
    visibleDrawer.value = false
    //刷新列表
    articleList();
}
//刷新抽屉表单
const clearArticleForm = () => {
    articleForm.value = {
        id : 1,
        title: "",
        content: "",
        description: "",
        category:"",
    }
}
//取消添加
const cancelDrawer = () => {
    visibleDrawer.value = false
}

//默认不显示对话框
const visibleDialog = ref(false)
//展示编辑对话框弹窗
const showDialog = (row: { title: string; content: string; description: string; id: any;category: string; }) => {
    clearArticleForm()
    visibleDialog.value = true
    //给编辑框回写原先信息
    articleForm.value.title = row.title
    articleForm.value.content = row.content
    articleForm.value.description = row.description
    articleForm.value.category = row.category
    articleForm.value.id = row.id
}
//为对话框添加响应数据
const updateArticleRef = ref()
//后台调用修改会员接口
const onUpdate = async () => {
    //点击修改后再进行二次校验
    await updateArticleRef.value?.validate().catch((err: any) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await updateArticleService(articleForm.value) as any;
    ElMessage.success(result.msg ? result.msg : '修改成功')
    //让对话框消失
    visibleDialog.value = false
    //刷新列表
    articleList();
}
//取消修改
const cancelDialog = () => {
    visibleDialog.value = false
}

//删除
const deleteArticle = (row: { id: any }) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await deleteArticleService(row.id) as any;
            ElMessage({
                type: 'success',
                message: result.msg ? result.msg : '删除成功',
            })
            articleList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
//批量删除
const arr = ref([])
const handleSelectionChange = (rows: any)=>{
    arr.value = rows.map((i: { id: any }) => i.id)
}
const deleteBatchArticle = () =>{
    if(arr.value.length === 0){
        ElMessage.error("请选择数据")
        return
    }
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let ids = toRaw(arr.value)
            let params = {
                ids:ids
            }
            let result = await deleteBatchArticleService(params) as any;
            ElMessage({
                type: 'success',
                message: result.msg ? result.msg : '删除成功',
            })
            articleList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>文章管理</span>
                <div>
                    <el-button type="primary" @click="visibleDrawer = true; clearArticleForm()">添加文章</el-button>
                    <el-button type="danger" @click="deleteBatchArticle()">批量删除</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item prefix-icon="name" label="文章标题：">
                <el-input v-model="title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item prefix-icon="name" label="文章分类：">
                <el-select placeholder="请选择" v-model="category" style="width: 200px" @focus="articleCategoryList()">
                            <el-option v-for="c in categories" :key="c" :label="c" :value="c">
                            </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="articleList()">搜索</el-button>
                <el-button @click="title = '',category = ''">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 文章列表 -->
        <el-table :data="article" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" width="100">
                <template v-slot="scope">
                    <!-- 序号实现自动增加且连续 -->
                    {{ (page - 1) * pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="文章标题" prop="title" show-overflow-tooltip width="150"></el-table-column>
            <el-table-column label="文章分类" prop="category" show-overflow-tooltip width="150"></el-table-column>
            <el-table-column label="文章内容" prop="content" width="200">
                <template v-slot="scope">
                    <el-button type="info" @click="showContent(scope.row.content)">显示内容</el-button>
                </template>
            </el-table-column>
            <el-table-column label="文章描述" prop="description" width="120"></el-table-column>
            <el-table-column label="发布人" prop="author" width="120"></el-table-column>
            <el-table-column label="发布时间" prop="createTime" width="200"></el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="{ row }">
                    <el-button :icon="Edit"  plain type="primary" @click="showDialog(row)">编辑</el-button>
                    <el-button :icon="Delete"  plain type="danger" @click="deleteArticle(row)">删除</el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" background
            layout="sizes,prev, pager,next,jumper,total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :total="total">
        </el-pagination>

        <!-- 显示富文本内容对话框 -->
        <el-dialog title="内容" v-model="visibleDialog1"  width="60%">
            <div class="w-e-text">
                <div v-html="content1"></div>
            </div>
            <div>
                <el-button type="primary" @click="visibleDialog1 = false">返 回</el-button>
            </div>
        </el-dialog>

        <!-- 抽屉中嵌套添加表单 -->
        <el-drawer v-model="visibleDrawer" title="添加文章" direction="rtl" destroy-on-close size="45%">
            <div>
                <el-form ref="addArticleRef" :model="articleForm" :rules="Rules">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="articleForm.title" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="分类" prop="category">
                        <el-input v-model="articleForm.category" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="描述" prop="description">
                        <el-input v-model="articleForm.description" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="内容">
                        <TextEditor v-model="articleForm.content"/>
                    </el-form-item>
                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDrawer();clearArticleForm()">取消</el-button>
                    <el-button type="primary" @click="onAdd">
                        添加
                    </el-button>
                </div>
            </div>
        </el-drawer>

        <!-- 对话框嵌套编辑表单 -->
        <el-dialog v-model="visibleDialog" title="修改文章" destroy-on-close>
            <div>
                <el-form ref="updateArticleRef" :model="articleForm" :rules="Rules">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="articleForm.title" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="分类" prop="category">
                        <el-input v-model="articleForm.category" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="描述" prop="description">
                        <el-input v-model="articleForm.description" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="内容">
                        <TextEditor  v-model="articleForm.content"/>
                    </el-form-item>
                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDialog();clearArticleForm()">取消</el-button>
                    <el-button type="primary" @click="onUpdate">
                        修改
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </el-card>
</template>


<style scoped lang="scss">
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>